const mysql = require('mysql');
const db = require('../datastore.js')
// 数据库配置
module.exports = {
    /**
     * 数据库配置
     */
    config: db.read().get('dataBase').find({type:'mysql'}).value().config,
    conn: null,
    /**
     * 创建连接池并连接
     * @param callback
     */
    openConn: function (callback) {
        var me = this;
        me.conn = mysql.createConnection(me.config);
    },
    /**
     * 释放连接池
     * @param conn
     */
    closeConn: function () {
        var me = this;
        me.conn.end(function (err) {
            console.log(err);
        });
    },
    /**
     * 执行连接
     * @param config
     */
    exec: function (config,callback) {
        const me = this;
        me.openConn();
        me.conn.query(config.sql, config.params, function (err, res) {
            if (err) {
                console.log(err);
                callback(false);
            } else if (callback) {
                callback(res);
            }
            // 关闭数据库连接
            me.closeConn();
        });
    },

    /**
     * 
     */
    test: function(callback){
        const me = this;
        me.openConn();
        let sql ="SELECT table_name name,TABLE_COMMENT value FROM INFORMATION_SCHEMA.TABLES WHERE table_type='base table' and table_schema = ? order by table_name asc";
        me.conn.query(sql,[me.config.database], function (err, res) {
            if (err) {
                console.log(err);
                callback(false);
            } else if (callback) {
                callback(true);
            }
            // 关闭数据库连接
            me.closeConn();
        });
    }
};